import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'action.dart';
import 'state.dart';

Reducer<PayTeacherListState> buildReducer() {
  return asReducer(
    <Object, Reducer<PayTeacherListState>>{
      PayTeacherListAction.loaded: _loaded,
      PayTeacherListAction.loading: _loading,
      PayTeacherListAction.listResult: _listResult,
    },
  );
}

PayTeacherListState _loading(PayTeacherListState state, Action action) {
  return state.clone()..isLoading = true;
}

PayTeacherListState _loaded(PayTeacherListState state, Action action) {
  return state.clone()..isLoading = false;
}

PayTeacherListState _listResult(PayTeacherListState state, Action action) {
  final Map<String, dynamic> data = action.payload;
  if (data == null) {
    return state;
  }

  int pageIndex = data['pageIndex'];
  final PayTeacherListState newState = state.clone()
    ..pageTotal = data['pageTotal']
    ..pageIndex = pageIndex;

  if (pageIndex == GlobalState.firstPageIndex + 1) {
    newState.items = data['items']; // reset if first page
  } else {
    newState.items.addAll(data['items']);
  }

  return newState;
}
